package test;
import java.io.ByteArrayInputStream;

import org.kxml2.io.KXmlParser;
import org.kxml2.kdom.Document;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;


public class TrataXML {

	public static Document getXML( int tamanhoCampos, int numCampos, int tamanhoHierarquia )
	 {

	 	String texto = "";
	 	Element element = new Element( );
	 	Element aux = null;
	 	Element campo = null;
	 	element.setName( "obj" + tamanhoHierarquia );


	 	// cria o obj mais interno e os campos dentro dele
	 	for ( int i = 1 ; i <= numCampos ; i++ )
	 	{
	 		// cria texto
	 		for ( int j = 0 ; j < tamanhoCampos ; j++ )
	 		{
	 			texto = texto + "a";
	 		}
	 		campo = new Element( );
	 		campo.setName( "campo" + i );
	 		campo.addChild( Node.TEXT, texto );
	 		element.addChild( Node.ELEMENT, campo );
	 	}

	 	// cria os campos mais externos
	 	for ( int i = tamanhoHierarquia - 1 ; i > 0 ; i-- )
	 	{
	 	 aux = new Element( );
	 	 aux.setName( "obj" + i );
	 	 aux.addChild( Node.ELEMENT, element );
	 	 element = aux;
	 	}
	  
	 	Document doc = new Document( );
	 	doc.addChild( 0, Node.ELEMENT, element );
	  
	 	return doc;
	 }

	/**************************************************************************************/
	 
	 
	 public static void extractXML(String xml)
	 {
		 String msg = "";
		 Document doc = new Document();
		 try
		 {
			 ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes());
			 KXmlParser parser = new KXmlParser();
			 parser.setInput(bais, null);
			 doc.parse(parser);
			 
		 }
		 catch(Exception e)
		 {
			 System.out.println(e.getMessage());
		 }
			 
		 Element element = null;
		 Element childElement = doc.getRootElement();
		 int i = 1;
		 boolean hasElement = true;
		 while (hasElement)
		 {
			 i++;
			 element = childElement;
			 msg = msg + childElement.getName() + " ";
			 try 
			 {
				 childElement = childElement.getElement(null, "obj"+i);
			 }
			 catch(Exception e)
			 {
				hasElement = false;
			 }
		 }
		 hasElement = true;
		 i = 1;
		 
		 while (hasElement)
		 { 
			 try 
			 {
				 childElement = element.getElement(null, "campo"+i);
				 msg = msg + " " + childElement.getName() + " = " + childElement.getChild(0).toString();
				 i++;
			 }
			 catch(Exception e)
			 {
				hasElement = false;
			 }
		 }
		 System.out.println(msg);
	 }
}
